package com.tan.androidtest.service;

import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.RemoteCallbackList;
import android.os.RemoteException;
import android.support.annotation.Nullable;

import com.tan.androidtest.ITestAidlInterface;
import com.tan.androidtest.ITestAidlInterfaceCallback;

/**
 * 测试自己写的AIDL service
 */

public class TestMyAIDLService extends Service {

    private int mProcess;//记录
    private Handler mHandler;
    private static final int MSG_UPDATE_PROCESS = 0x111;
    private RemoteCallbackList<ITestAidlInterfaceCallback> mCallbackRemoteCallbackList = new RemoteCallbackList<>();

    @Override
    public void onCreate() {
        super.onCreate();
        if (mHandler == null) {
            mHandler = new MyHandler();
        }
        mHandler.sendEmptyMessageDelayed(MSG_UPDATE_PROCESS, 3000);
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return new MyITestStub();
    }

    private class MyHandler extends Handler {

        @Override
        public void handleMessage(Message msg) {
            mProcess += 3;
            mHandler.sendEmptyMessageDelayed(MSG_UPDATE_PROCESS, 3000);

            if (mCallbackRemoteCallbackList != null) {
                int i = mCallbackRemoteCallbackList.beginBroadcast();
                while (i > 0) {
                    i--;
                    try {
                        mCallbackRemoteCallbackList.getBroadcastItem(i).onCallback(mProcess);
                    } catch (RemoteException e) {
                        e.printStackTrace();
                    }
                }
                mCallbackRemoteCallbackList.finishBroadcast();
            }
        }
    }

    public class MyITestStub extends ITestAidlInterface.Stub {

        @Override
        public void registerCallback(ITestAidlInterfaceCallback callback) throws RemoteException {
            mCallbackRemoteCallbackList.register(callback);
        }

        @Override
        public void unRegisterCallback(ITestAidlInterfaceCallback callback) throws RemoteException {
            mCallbackRemoteCallbackList.unregister(callback);
        }


    }


}
